let mysql = require("mysql");
let {options} = require("./config");

class Db{
  constructor({host="localhost",user="root",password="",database=""}){
    this.option = {
      host,
      user,
      password,
      database
    }
    this.connection = mysql.createConnection(this.option);
  }
  // initConn(){
  //   this.connection =  mysql.createConnection(this.option);
  //   // this.connection.connect();
  //   return new Promise((resolve,reject)=>{
  //     this.connection.connect((err)=>{
  //       if(!err){
  //         // 连接成功后，将连接对象返回
  //         resolve( this.connection )
  //       }else{
  //         reject(err)
  //       }
  //     });
  //   })
  // }
  async query(sql,arr){
    // 每次执行CRUD操作时，重新创建连接
    // let conn = await this.initConn()
    return new Promise((resolve,reject)=>{
      this.connection.query(sql,arr,(err,result)=>{
        if(!err){
          resolve( result )
        }else{
          reject(err)
        }
      })
    })
  }
  close(){
    this.connection.end()
  }
}

let db = new Db(options);
module.exports = db;
